// pagesA/loginI/loginI.js
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
import {
  validate
} from '../../common/js/validate'
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobileDisable: true,
    msg: '发送验证码',
    count: 60,
    timer: null,
    send: false,
    disabled: true,
    tabNav: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      tabNav: options.tabNav
    })
    qqmapsdk = new QQMapWX({
      key: app.globalData.key
    })
    wx.setStorageSync('tabNav', options.tabNav)
  },
  toggle(e) {
    this.setData({
      disabled: !e.detail.checked
    })
  },
  registerLink() {
    wx.redirectTo({
      url: '../register/register?tabNav=' + this.data.tabNav,
    })
  },
  imFun(phoneNumber) {

  },
  bindinputmobile: function (e) {
    let that = this
    if (e.detail.value.length == 11) {
      let urls = ''
      if (this.data.tabNav == 0) {
        urls = '/customer/check/'
      } else {
        urls = '/medical/check/'
      }
      wx.request({
        url: that.data.tabNav == 3?app.globalData.serverUrlgdb +  urls + e.detail.value:app.globalData.serverUrl +  urls + e.detail.value,
        method: 'GET',
        success: (res => {
          if (res.data.code == 200) {
            this.setData({
              mobileDisable: !e.detail.value,
              phoneNumber: e.detail.value,
              mobileErr: '',
              codeErr: ''
            })
          } else {
            this.setData({
              mobileDisable: e.detail.value,
              phoneNumber: e.detail.value,
              mobileErr: '',
              codeErr: ''
            })
            app.showMsg(res.data.message)
          }
        })
      })
    } else {
      if(e.detail.value){
        this.setData({
          mobileDisable: e.detail.value,
          phoneNumber: e.detail.value,
          mobileErr: '',
          codeErr: ''
        })
      }else{
        this.setData({
          mobileDisable: !e.detail.value,
          phoneNumber: e.detail.value,
          mobileErr: '',
          codeErr: ''
        })
      }
    }
  },
  bindinputcode: function (e) {
    this.setData({
      code: e.detail.value
    })
  },
  tapSendCode: function () {
    const self = this
    if (!validate(this, 'phoneNumber')) {
      return
    }
    wx.showLoading({
      mask: true
    })
    if (this.data.send) {
      return
    }
    self.setData({
      send: true,
      mobileDisable: true
    })
    wx.request({
      url: (self.data.tabNav == 3?app.globalData.serverUrlgdb:app.globalData.serverUrl) + '/user/code/' + self.data.phoneNumber,
      method: 'GET',
      success(res) {
        wx.hideLoading()
        self.selectComponent('#codeSH').show()
        setTimeout(() => {
          self.selectComponent('#codeSH').hide()
        }, 1500);
        self.timer = setInterval(() => {
          let count = self.data.count - 1
          let msg = count + '秒后重新发送'
          if (count === 0) {
            clearInterval(self.timer)
            msg = "重新发送"
            self.setData({
              send: false,
              count: 60,
              msg: msg,
              mobileDisable: false
            })
            return
          }
          self.setData({
            count: count,
            msg: msg
          })
        }, 1000)
      },
      error(data) {
        self.setData({
          send: false
        })
        app.showMsg(data.msg)
      }
    })
  },
  showDialog({
    title,
    tip,
    icon
  } = {}) {
    this.setData({
      title: title,
      tip: tip,
      icon: icon
    })
    this.selectComponent('#dialog').show()
  },
  bindtapLogin() {
    let that = this
    if(that.data.phoneNumber=='' || that.data.phoneNumber==undefined || that.data.code=='' || that.data.code==undefined){
      that.showDialog({
        title: '请正确输入',
        icon: 'warning',
        tip: ['手机号及验证码']
      })
      return
    }
    wx.getSystemInfo({
      success (resd) {
        let locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
        let locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
        if (locationEnabled == false) {
          that.showDialog({
            title: '手机未打开定位功能',
            icon: 'fail',
            tip: ['']
          })
        }else if(locationAuthorized == false){
          that.showDialog({
            title: '微信未授权定位权限',
            icon: 'fail',
            tip: ['请前往设置-应用内打开','微信定位信息权限']
          })
        }
        else {
          wx.getSetting({
            success: res => {
              console.log(res);
              let authSetting = res.authSetting
              if (authSetting['scope.userLocation']) {
                app.loginCode().then(resCode => {
                  let data = {
                    code: that.data.code,
                    phoneNumber: that.data.phoneNumber,
                    wxCode: resCode
                  }
                  let urls = that.data.tabNav == 1 ? '/medical/login' :that.data.tabNav == 3 ?'/medical/login':  '/customer/login'
                  console.log(app.globalData.serverUrlgdb,that.data.tabNav);
                  wx.request({
                    url: that.data.tabNav == 3?app.globalData.serverUrlgdb + urls:app.globalData.serverUrl + urls,
                    method: 'POST',
                    data,
                    success: (res => {
                      let resp = res.data
                      if (resp.code == 200) {
                        wx.setStorageSync('token', resp.data.token)
                        app.getUserInfo()
                        // 已授权 || 尚未进行操作
                        if (that.data.tabNav == 1) {
                          //用于机构登录时校验账号提示
                          // this.selectComponent('#dialogSettinull').show()
                          wx.setStorageSync('token1', resp.data.token)
                          wx.reLaunch({
                            url: '/pages/workbench/workbench',
                          })
                        } else if(that.data.tabNav == 3){
                          wx.setStorageSync('token3', resp.data.token)
                          wx.reLaunch({
                            url: '/pagesB/index/index',
                          })
                        } else {
                          if (!wx.getStorageSync('addresconter')) {
                            wx.getLocation({
                              type: 'gcj02',
                              success(res) {
                                const latitude = res.latitude
                                const longitude = res.longitude
                                console.log(res, '微信获取经纬度');
                                qqmapsdk.reverseGeocoder({
                                  location: {
                                    latitude: latitude,
                                    longitude: longitude
                                  },
                                  success: (res => {
                                    let resultData = res.result.address_component
                                    console.log(res.result.address_component, '地图调用获取位置信息');
                                    let addresconter = resultData.province + ' ' + resultData.city + ' ' + resultData.district
                                    wx.setStorageSync('addresconter', addresconter)
                                    let address = {
                                      province: resultData.province,
                                      city: resultData.city,
                                      areas: resultData.district
                                    }
                                    wx.setStorageSync('address', address)
                                    wx.reLaunch({
                                      url: '/pagesA/waiters/waiters',
                                    })
                                  })
                                })
                              }
                            })
                          } else {
                            wx.reLaunch({
                              url: '/pagesA/waiters/waiters',
                            })
                          }
                        }
                      } else {
                        app.showMsg(resp.message)
                      }
                    })
                  })
                })
              } else {
                if (authSetting['scope.userLocation'] == undefined) {
                  wx.authorize({
                    scope: 'scope.userLocation',
                    success(resp) {
                      console.log(resp);
                      if (resp.errMsg == "authorize:ok") {
                        that.bindtapLogin()
                      }
                    }
                  })
                } else {
                  that.selectComponent('#dialogSetti').show()
                }
              }
            }
          })
        }
      },
      fail(){
        that.showDialog({
          title: '手机未打开定位功能',
          icon: 'fail',
          tip: ['']
        })
      }
    })

  },
  bindtapSetting() {
    this.selectComponent('#dialogSetti').hide()
    wx.openSetting()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(wx.getStorageSync('tabNav')==0 && !wx.getStorageSync('ty')){
      wx.showModal({
        title: '登录授权',
        content: '继续使用小程序将获取相关权限，如：手机号、蓝牙、地理位置等。手机号用作登录账号，地理位置为了获取当前所在地区医院治疗项目。',
        success (res) {
          if (res.confirm) {
            // console.log('用户点击确定')
          } else if (res.cancel) {
            wx.getSystemInfo({
              success (resd) {
                let locationEnabled = resd.locationEnabled; //判断手机定位服务是否开启
                let locationAuthorized = resd.locationAuthorized; //判断定位服务是否允许微信授权
                if (locationEnabled == false) {
                  that.showDialog({
                    title: '手机未打开定位功能',
                    icon: 'fail',
                    tip: ['']
                  })
                }else if(locationAuthorized == false){
                  that.showDialog({
                    title: '微信未授权定位权限',
                    icon: 'fail',
                    tip: ['请前往设置-应用内打开','微信定位信息权限']
                  })
                }
                else {
                  wx.getSetting({
                    success: res => {
                      console.log(res);
                      let authSetting = res.authSetting
                      if (authSetting['scope.userLocation']) {
                        if (!wx.getStorageSync('addresconter')) {
                          wx.getLocation({
                            type: 'gcj02',
                            success(res) {
                              const latitude = res.latitude
                              const longitude = res.longitude
                              console.log(res, '微信获取经纬度');
                              qqmapsdk.reverseGeocoder({
                                location: {
                                  latitude: latitude,
                                  longitude: longitude
                                },
                                success: (res => {
                                  let resultData = res.result.address_component
                                  console.log(res.result.address_component, '地图调用获取位置信息');
                                  let addresconter = resultData.province + ' ' + resultData.city + ' ' + resultData.district
                                  wx.setStorageSync('addresconter', addresconter)
                                  let address = {
                                    province: resultData.province,
                                    city: resultData.city,
                                    areas: resultData.district
                                  }
                                  wx.setStorageSync('address', address)
                                  wx.redirectTo({
                                    url: '/pagesA/waiters/waiters',
                                  })
                                })
                              })
                            }
                          })
                        } else {
                          wx.redirectTo({
                            url: '/pagesA/waiters/waiters',
                          })
                        }
                      } else {
                        if (authSetting['scope.userLocation'] == undefined) {
                          if (!wx.getStorageSync('addresconter')) {
                            wx.getLocation({
                              type: 'gcj02',
                              success(res) {
                                const latitude = res.latitude
                                const longitude = res.longitude
                                console.log(res, '微信获取经纬度');
                                qqmapsdk.reverseGeocoder({
                                  location: {
                                    latitude: latitude,
                                    longitude: longitude
                                  },
                                  success: (res => {
                                    let resultData = res.result.address_component
                                    console.log(res.result.address_component, '地图调用获取位置信息');
                                    let addresconter = resultData.province + ' ' + resultData.city + ' ' + resultData.district
                                    wx.setStorageSync('addresconter', addresconter)
                                    let address = {
                                      province: resultData.province,
                                      city: resultData.city,
                                      areas: resultData.district
                                    }
                                    wx.setStorageSync('address', address)
                                    wx.redirectTo({
                                      url: '/pagesA/waiters/waiters',
                                    })
                                  })
                                })
                              }
                            })
                          } else {
                            wx.redirectTo({
                              url: '/pagesA/waiters/waiters',
                            })
                          }
                        } else {
                          that.selectComponent('#dialogSetti').show()
                        }
                      }
                    }
                  })
                }
              },
              fail(){
                that.showDialog({
                  title: '手机未打开定位功能',
                  icon: 'fail',
                  tip: ['']
                })
              }
            })
            
          }
        }
      })
    }
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})